package com.xiaoshuidi.cloud.module.rooms.utils.tree;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class TreeFactory<K,T extends TreeNode<K,T>> implements Serializable {
    private static final long serialVersionUID = -6171596383219073138L;

    public List<T> bulidTree(List<T> nodeList){
         HashMap<K, T> nodeMap = new HashMap<>();
        for (T node : nodeList) {
            nodeMap.put(node.getId(),node);
        }
        return bulidTree(nodeMap);
    }

    public List<T> bulidTree(HashMap<K,T> nodeMap) {
        return findParent(nodeMap);
    }

    public List<T> findParent(HashMap<K,T> nodeMap) {
        //循环结束后可以移除掉的节点
        List<K> removeNodes = new ArrayList<>();

        for (T node : nodeMap.values()) {
             T pNode = nodeMap.get(node.getPid());
             if (pNode!=null&&!pNode.getId().equals(node.getId())){
                 pNode.addChild(node);
                 removeNodes.add(node.getId());
             }
        }
        //删除已经找到父节点的节点
        removeNodes.forEach(nodeMap::remove);
        //遍历map,直到把所有非根节点删除
        if (removeNodes.size()>0){
            findParent(nodeMap);
        }
        return new ArrayList<>(nodeMap.values());
    }
}
